<?php


namespace haibao\jiepai\business;

use \haibao\jiepai\data\Media as MediaData;
use \haibao\jiepai\model\filter\media\CmsMediaFiles as CmsMediaFilesFilter;



class Media extends Base{
    
    public static function getAudioListByFilter($filter){


        $data = new MediaData();
        return $data->getAll($filter);
    }

    public static function getAudioById($audioId){
        if(!$audioId){
            throw new BusinessException('音频ID不存在');
        }
        $data = new MediaData();
        return $data->getOneById((int)$audioId);
    }
    
    public static function getAudioListById($audioIds){
        if(!$audioIds){
            throw new BusinessException('音频ID不存在');
        }
        $data = new MediaData();
        return $data->getAudioListById($audioIds);
    }

    public static function saveUpload($file){
        $basePath = '/jiepai-1/audios/'.date('Y').DIRECTORY_SEPARATOR;
        $fullPath = $basePath.microtime(true);
        $extension = pathinfo($file['name']);
        $fullPath .= '.' . strtolower(isset($extension['extension']) ? $extension['extension'] : 'mp3');
        $path = str_replace(array('/', '\\'), '/', $fullPath);
        $savePath = \haibao\frame\Environment::path().$path;
        \haibao\cms\business\ImageLibrary::createDir($savePath);
        move_uploaded_file($file['tmp_name'], $savePath);
        return $path;
    }

    public static function saveAudio($audioModel){

        if(!$audioModel->Title){
            throw new BusinessException('音频名称必填');
        }
        if(!$audioModel->Name){
            throw new BusinessException('请上传音频资源');
        }
        if(!$audioModel->Singer){
            throw new BusinessException('歌手名称必填');
        }
        $audioModel->Creator = \haibao\cms\business\Base::getCurrentUser()->Id;
        $data = new MediaData();
        if($audioModel->Id){
            $data->updateById((int)$audioModel->Id,array(
                CmsMediaFilesFilter::CONDITION_FIELD_NAME_TITLE=>$audioModel->Title,
                CmsMediaFilesFilter::CONDITION_FIELD_NAME_NAME=>$audioModel->Name,
                CmsMediaFilesFilter::CONDITION_FIELD_NAME_SINGER=>$audioModel->Singer,
                CmsMediaFilesFilter::CONDITION_FIELD_NAME_SIZE=>$audioModel->Size,
                CmsMediaFilesFilter::CONDITION_FIELD_NAME_COVER=>$audioModel->Cover,
                CmsMediaFilesFilter::CONDITION_FIELD_NAME_ALBUM=>$audioModel->Album,
            ));
        }else{
            $audioModel->CreateTime = new \DateTime();
            $audioModel->Flag = 0;
            $data->add($audioModel);
        }
    }

    public static function updateAudioData($audioId, $updateData){
        if(!$audioId){
            throw new BusinessException('音频Id不出在');
        }
        $data = new MediaData();
        $data->updateById($audioId, $updateData);
    }
}